package main.com;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.PublicKey;
import java.util.Enumeration;

import javax.security.auth.PrivateCredentialPermission;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.sax.TextElementListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class TestSendActivity extends Activity {
	
	private TextView serverStatus;
	public static String SERVERIP="";
	public static int SERVERPORT=8080;
	public Handler handler=new Handler();
	private ServerSocket serverSocket;
	public  String result="None";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView myTextView =(TextView)findViewById(R.id.textViewReceive);
        final EditText myEditText=(EditText)findViewById(R.id.EditTextSend);
        //final Button button =(Button)findViewById(R.id.btnSend);
        serverStatus=(TextView)findViewById(R.id.textViewReceive);
        ServerThread abc = new ServerThread();
       //abc.run();
        SERVERIP = getLocalIpAddress();
        // abc.run();
        Thread fst = new Thread(new ServerThread());
        fst.start();
				
		}
    public class ServerThread implements Runnable {
    	
    		        public void run() {
    		            try {
    		                if (SERVERIP != null) {
    	                    handler.post(new Runnable() {
    		                        @Override
    		                        public void run() {
    		                     serverStatus.setText("Listening on IP: " + SERVERIP);
    		                      }
    		                    });
    		                    serverSocket = new ServerSocket(SERVERPORT);
    		                    while (true) {
    		                    	serverStatus.setText("Listening on IP: " + SERVERIP);
    		                        // listen for incoming clients
    		                        Socket client = serverSocket.accept();
    		                        handler.post(new Runnable() {
    		                            @Override
    		                            public void run() {
    		                                serverStatus.setText("Connected.");
    		                            }
    		                        });
    		 
    		                        try {
    		                            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    		                            String line = null;
    		                            while ((line = in.readLine()) != null) {
    		                                Log.d("ServerActivity", line);
    		                                serverStatus.setText(line);
    		                                result=line.toString();
    		                                handler.post(new Runnable() {
    		                                    @Override
    	                                    public void run() {
    		                                        // set something
    		                                        
    		                                    }
    		                                });
    		                            }
    	                            break;
    		                        } catch (Exception e) {
    		                            handler.post(new Runnable() {
    		                                @Override
    		                                public void run() {
    		                                    serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
    		                                }
    		                            });
    		                            e.printStackTrace();
    		                        }
    		                    }
    		                } else {
    		                    handler.post(new Runnable() {
    		                        @Override
    		                        public void run() {
    		                            serverStatus.setText("Couldn't detect internet connection.");
    		                        }
    		                    });
    		                }
    		            } catch (Exception e) {
    		                handler.post(new Runnable() {
    		                    @Override
    		                    public void run() {
    		                        serverStatus.setText("Error");
    		                    }
    		                });
    		                e.printStackTrace();
    		            }
    		            serverStatus.setText(result);
    		        }
    		    }
    		 
    		    // gets the ip address of your phone's network
    		    private String getLocalIpAddress() {
    		        try {
    		            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
    		                NetworkInterface intf = en.nextElement();
    		                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
    		                    InetAddress inetAddress = enumIpAddr.nextElement();
    		                    if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
    		                }
    		            }
    		        } catch (SocketException ex) {
    		            Log.e("ServerActivity", ex.toString());
    		        }
    		        return null;
    		    }
    		 
    		    @Override
    		    protected void onStop() {
    		        super.onStop();
    		        try {
    		             // make sure you close the socket upon exiting
    		             serverSocket.close();
    		         } catch (IOException e) {
    		             e.printStackTrace();
    		         }
    		    }
    		 
    		}



    /*public void send()
    {
    	try {
			client= new Socket("10.0.2.2",8080);
			inputstream = new DataInputStream(client.getInputStream());
			outputstream = new DataOutputStream(client.getOutputStream());
			while(true)
			{
				String s = myEditText.toString();
				
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    
    
    // de danh client 
     * 
     * 
     * 
     * client= new Socket("10.0.2.2",8080);
					inputstream = new DataInputStream(client.getInputStream());
					outputstream = new DataOutputStream(client.getOutputStream());
					String message = "adada";
						
						outputstream.writeUTF(message);
						//Log.d("TCP", "C: Sending: '" + message + "'");
						//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
						BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
						
						String bacd= in.readLine();
						myTextView.setText(bacd);
 */
